<template>
  <div class="xtx-city" ref="target">
    <div class="select" @click="toggle()">
      <span class="value" v-if="fullLocation">{{ fullLocation }}</span>
      <span class="placeholder" v-else>请选择配送地址</span>
      <i class="iconfont icon-angle-down"></i>
    </div>
    <div class="option" v-if="isShow">
      <div class="loading" v-if="!list.length"></div>
      <span class="ellipsis" @click="changeItem(item)" v-for="item in list" :key="item.code">{{ item.name }}</span>
    </div>
  </div>
</template>

<script>
// 获取城市数据
// 1. 数据在哪里？https://yjy-oss-files.oss-cn-zhangjiakou.aliyuncs.com/tuxian/area.json
// 2. 何时获取？打开城市列表的时候，做个内存中缓存
// 3. 怎么使用数据？定义计算属性，根据点击的省份城市展示
import { computed, ref, reactive } from 'vue'
import { onClickOutside } from '@vueuse/core'
import axios from 'axios'

// 获取城市数据并实现内存缓存
const getCityList = async () => {
  // 如果内存中有城市数据，直接返回
  if (window.cityList) {
    // console.log('读取缓存中的数据')
    return window.cityList
  } else {
    // 内存中没有城市数据，发送请求，获取城市数据
    const { data } = await axios.get('https://yjy-oss-files.oss-cn-zhangjiakou.aliyuncs.com/tuxian/area.json')
    // 把数组存储到 window 对象中缓存起来
    window.cityList = data
    // console.log('网络请求获取')
    return data
  }
}
export default {
  name: 'XtxCity',
  props: {
    fullLocation: {
      type: String,
      default: ''
    }
  },
  setup(props, { emit }) {
    const isShow = ref(false)
    const cityList = ref([])

    // 显示
    const show = async () => {
      isShow.value = true
      // 发送请求获取城市列表
      //   console.log('发送请求获取城市列表')
      cityList.value = await getCityList()

      // 打开时要重置地址
      for (const key in address) {
        address[key] = ''
      }
    }

    // 隐藏
    const hide = () => {
      isShow.value = false
    }

    const toggle = () => {
      isShow.value ? hide() : show()
    }

    // 点击元素外(空白区)隐藏
    const target = ref(null)
    onClickOutside(target, () => {
      // console.log('点击目标元素外')
      hide()
    })

    // 用户选择的地址
    const address = reactive({
      provinceCode: '',
      provinceName: '',
      cityCode: '',
      cityName: '',
      countyCode: '',
      countyName: '',
      fullLocation: '' // 用于显示到组件的中文地址
    })

    // 通过计算属性计算出当前所需展示的列表
    const list = computed(() => {
      // 情况1：返回省份
      let currList = cityList.value
      // 情况2：确定的省的编码，就返回对应的市
      if (address.provinceCode) {
        currList = currList.find((item) => item.code === address.provinceCode).areaList
      }
      // 情况3：确定的市的编码，返回区/县
      if (address.cityCode) {
        currList = currList.find((item) => item.code === address.cityCode).areaList
      }

      // 用于页面展示的列表
      return currList
    })

    // 用户点击 收集对应地址编码的地址名称
    const changeItem = ({ level, code, name }) => {
      // 省：level === 0
      //  市：level === 1
      // 区/县：level === 2
      if (level === 0) {
        address.provinceCode = code
        address.provinceName = name
      } else if (level === 1) {
        address.cityCode = code
        address.cityName = name
      } else if (level === 2) {
        address.countyCode = code
        address.countyName = name

        // 选择完成后隐藏地址选择面板
        hide()

        // 拼接中文名字
        address.fullLocation = `${address.provinceName} ${address.cityName} ${address.countyName}`

        // 父组件可以通过自定义事件获取地址
        emit('change', address)
      }
    }

    return { isShow, toggle, target, list, changeItem, address }
  }
}
</script>

<style scoped lang="less">
.xtx-city {
  display: inline-block;
  position: relative;
  z-index: 400;
  .select {
    border: 1px solid #e4e4e4;
    height: 30px;
    padding: 0 5px;
    line-height: 28px;
    cursor: pointer;
    &.active {
      background: #fff;
    }
    .placeholder {
      color: #999;
    }
    .value {
      color: #666;
      font-size: 12px;
    }
    i {
      font-size: 12px;
      margin-left: 5px;
    }
  }
  .option {
    width: 542px;
    border: 1px solid #e4e4e4;
    position: absolute;
    left: 0;
    top: 29px;
    background: #fff;
    min-height: 30px;
    line-height: 30px;
    display: flex;
    flex-wrap: wrap;
    padding: 10px;
    .loading {
      height: 290px;
      width: 100%;
      background: url(~@/assets/images/loading.gif) no-repeat center;
    }
    > span {
      width: 130px;
      text-align: center;
      cursor: pointer;
      border-radius: 4px;
      padding: 0 3px;
      &:hover {
        background: #f5f5f5;
      }
    }
  }
}
</style>
